/**
 * Copyright (c) 2018-2028, DreamLu 卢春梦 (qq596392912@gmail.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.core.cloud.header;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.core.tool.utils.WebUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.util.PatternMatchUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

/**
 * feign 传递Request header
 *
 * <p>
 *     https://blog.csdn.net/u014519194/article/details/77160958
 *     http://tietang.wang/2016/02/25/hystrix/Hystrix%E5%8F%82%E6%95%B0%E8%AF%A6%E8%A7%A3/
 *     https://github.com/Netflix/Hystrix/issues/92#issuecomment-260548068
 * </p>
 *
 * @author L.cm
 */
public class BladeFeignRequestHeaderInterceptor implements RequestInterceptor {

	@Override
	public void apply(RequestTemplate requestTemplate) {
//		Map<String, Collection<String>> _queries = requestTemplate.queries();
//		if (!_queries.isEmpty()) {
//			//由于在最新的  RFC 3986  规范，+号是不需要编码的，因此spring 实现的是这个规范，这里就需要参数中进行编码先，兼容旧规范。
//			Map<String, Collection<String>> encodeQueries = new HashMap<String, Collection<String>>(_queries.size());
//
//			Iterator<String> iterator = _queries.keySet().iterator();
//			Collection<String> encodeValues = null;
//			while (iterator.hasNext()) {
//				encodeValues = new ArrayList<>();
//
//				String key = iterator.next();
//				Collection<String> values = _queries.get(key);
//
//				for (String _str : values) {
//					_str = _str.replace("%26", "&");
//					encodeValues.add(_str);
//				}
//				encodeQueries.put(key, encodeValues);
//			}
//			requestTemplate.queries(null);
//			requestTemplate.queries(encodeQueries);
//		}

		HttpHeaders headers = BladeHttpHeadersContextHolder.get();
		if (headers == null){
			HttpServletRequest request = WebUtil.getRequest();
			if (request == null) {
				return;
			}
			headers = new HttpHeaders();
			List<String> allowHeadsList = new ArrayList<>(Arrays.asList("X-Real-IP", "x-forwarded-for", "authorization", "Authorization", "hc-auth"));
			// 传递请求头
			Enumeration<String> headerNames = request.getHeaderNames();
			if (headerNames != null) {
				while (headerNames.hasMoreElements()) {
					String key = headerNames.nextElement();
					// 只支持配置的 header
					if (allowHeadsList.contains(key)) {
						String values = request.getHeader(key);
						// header value 不为空的 传递
						if (StringUtil.isNotBlank(values)) {
							headers.add(key, values);
						}
					}
				}
			}
		}
		if (headers != null && !headers.isEmpty()) {
			headers.forEach((key, values) -> {
				values.forEach(value -> requestTemplate.header(key, value));
			});
		}
	}

	public static void main(String[] args) throws UnsupportedEncodingException {
		String _str = "1F&999";
		_str = URLDecoder.decode(_str, "UTF-8");
		System.out.println(_str);
		_str = URLEncoder.encode(_str, "UTF-8");
		System.out.println(_str);

	}
}
